from http.server import HTTPServer, BaseHTTPRequestHandler
import os

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        # 获取请求路径
        path = self.path.strip('/')
        
        # 设置服务路径
        server_path = './project/'
        
        # 如果路径以/结尾或者为空，尝试寻找索引文件
        if path in ('', '/'):
            if os.path.exists(os.path.join(server_path+path, 'index.html')):
                path = 'index.html'
            elif os.path.exists(os.path.join(server_path+path, 'index.htm')):
                path = 'index.htm'
            else:
                if os.path.isdir(server_path+path):

                    # 发送200状态码和文件内容
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    for i in os.listdir(full_path):
                        self.wfile.write('<a href="./"'+i+'>'+i+'</a>');
                else:
                    # 如果文件不存在，发送404状态码
                    self.send_error(404, 'File not found')
        if 'config.json' in path:
            self.send_error(403, '拒绝提供 config.json')

        # 获取文件完整路径
        full_path = os.path.join(server_path, path)
        print(full_path)
        if os.path.isdir(full_path):

            # 发送200状态码和文件内容
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            for i in os.listdir(full_path):
                self.wfile.write('<a href="./"'+i+'>'+i+'</a>');

        # 检查文件是否存在且安全
        if os.path.exists(full_path) and not os.path.isdir(full_path):
            # 读取文件内容
            with open(full_path, 'rb') as file:
                content = file.read()
            # 发送200状态码和文件内容
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(content)
        else:
            # 如果文件不存在，发送404状态码
            self.send_error(404, 'File not found')

# 指定服务器地址和端口
address = ('', 8000)

# 创建HTTP服务器，并设置处理程序
httpd = HTTPServer(address, SimpleHTTPRequestHandler)

print('Serving HTTP on port 8000...')
# 开始监听和服务
import threading 
t = threading.Thread(name='debug http server' , target=httpd.serve_forever)
t.start()